<template>
	<view>
		<view class="slideshow">
			<view v-if="!islogin">
				<view class="ToddayRenwu">
					<!-- <image src="/static/logo.jpg" style="width: 100%;height: 654rpx;" mode=""></image> -->
					<u-parse @imgtap="imgtap" :html="system.stpe1"></u-parse>
				</view>
			</view>
			<view v-else>
				<view class="ToddayRenwu" v-if="!istodaysign">
					<view v-if="isToddayRenwu">
						<u-parse @imgtap="imgtap" :html="ToddayRenwu.data"></u-parse>
					</view>
					<view v-else>
						<!-- <image src="/static/jmwq-bg2.svg" style="width: 100%;" mode=""></image> -->
						<u-parse @imgtap="imgtap" :html="system.stpe2"></u-parse>
					</view>
				</view>
				<view class="ToddayRenwu" v-else-if="istodaysign">
					<!-- <image src="/static/jmwq-bg3.svg" style="height: 900rpx;width: 100%;" mode=""></image> -->
					<u-parse @imgtap="imgtap" :html="system.stpe3"></u-parse>
				</view>
			</view>
		</view>
		<view class="indexBody">
			<view class="inputBar">
				<!-- 注册登陆 -->
				<form v-if="!islogin">
					<button form-type="submit" @click="join" :style="{backgroundColor:system.color,color:system.frontColor}" class="joinBtn">加入芥末围棋</button>
				</form>
				<view v-else>
					<!-- 今日打卡 -->
					<view v-if="!istodaysign">
						<view v-if="isToddayRenwu">
							<input v-if="!isphoneNum" @input="onKeyInput" placeholder-class="phoneInputplaceholder" name="phoneNum"
							 placeholder="手机号" class="phoneInput" :style="{backgroundColor:system.color,color:system.frontColor}" />
							<button class="joinBtn" :style="{backgroundColor:system.color,color:system.frontColor}" open-type="getUserInfo"
							 @getuserinfo="getuserinfo" :disabled="!isToddayRenwu">前往打卡</button>
						</view>
						<button class="joinBtn" :style="{backgroundColor:system.color,color:system.frontColor}" v-else @click="lookSign">我的打卡</button>
					</view>
					<view v-else-if="istodaysign">
						<button class="joinBtn" :style="{backgroundColor:system.color,color:system.frontColor}" @click="goTosharePage(true)">查看详情</button>
						<button class="joinBtn" :style="{backgroundColor:system.color,color:system.frontColor}" @click="lookSign">我的打卡</button>
					</view>
				</view>
				<view class="wanfa" @click="this.$data.postShow = true">
					查看玩法说明
				</view>
			</view>
			<!-- 玩法弹窗 -->
			<u-popup v-model="postShow" mode="center" closeable>
				<!-- <image src="/static/wanfa.jpg" style="width: 648rpx;height: 1152rpx;" mode=""></image> -->
				<u-parse :html="system.wanfa" :tag-style="style"></u-parse>
			</u-popup>
			<!-- 查看打卡弹窗 -->
			<u-popup v-model="show" mode="bottom" safe-area-inset-bottom>
				<scroll-view scroll-y="true" style="height: 1000rpx;">
					<u-empty v-if="signData.length < 1" text="无历史打卡记录" mode="list"></u-empty>
					<view v-else class="" style="margin: 48rpx;">
						<u-time-line>
							<view v-for="(item,index) in signData" :key="index">
								<u-time-line-item nodeTop="2">
									<template v-slot:node>
										<view class="u-node" v-if="item.shenhe" :style="{background: system.color}">
											<u-icon name="pushpin-fill" color="#fff" :size="24"></u-icon>
										</view>
										<view class="u-node" v-else style="background: #D0D0D0;">
											<u-icon name="pushpin-fill" color="#fff" :size="24"></u-icon>
										</view>
									</template>
									<template v-slot:content>
										<view>
											<view class="u-order-title" v-if="item.shenhe">已打卡</view>
											<view class="u-order-title" v-else>审核中</view>
											<view class="u-order-desc" @click="goTosharePage(item._id)">{{item.likeOpenid.length}}人已为您点赞</view>
											<view class="u-order-desc" @click="lookImage(item.fileID)">查看打卡照片</view>
											<view class="u-order-time">{{item.signTime2}}</view>
										</view>
									</template>
								</u-time-line-item>
							</view>
						</u-time-line>
					</view>
				</scroll-view>
			</u-popup>
		</view>
	</view>
</template>

<script>
	const db = wx.cloud.database()
	const _ = db.command
	export default {
		data() {
			return {
				phoneNum: '',
				islogin: false, //是否登录
				istodaysign: false, //是否打卡
				show: false,
				signData: [], //打卡数据
				postShow: false, //是否显示玩法介绍
				ToddayRenwu: [], //今日打卡任务
				ToddayRenwuNewDate: '', //打卡任务时间
				isShare: false, //是否
				toadySignId: '', //今日打卡_id
				isToddayRenwu: false, //今天是否有任务
				isphoneNum: true, //是否完整手机号
				nameID: "jmwq",
				system: [],
				style: {
					// 字符串的形式
					img: 'max-width: 550rpx'
				}
			}
		},
		onLoad(query) {
			//获取
			wx.cloud.callFunction({
				name: 'echo',
				data: {
					action: "getSystem",
					nameID: this.$data.nameID
				}
			}).then(res => {
				uni.setStorageSync('system', res.result.data[0]);
				this.$data.system = uni.getStorageSync('system')
				this.$data.system.frontColor = this.$data.system.frontColor ? '#000000' : '#ffffff'
				wx.setNavigationBarTitle({
					title: this.$data.system.name
				})
				wx.setNavigationBarColor({
					frontColor: this.$data.system.frontColor,
					backgroundColor: this.$data.system.color,
					animation: {
						duration: 400,
						timingFunc: 'easeIn'
					}
				})
				this.getlogin()
			})

		},
		onShareAppMessage(res) {
			if (res.from === 'button') { // 来自页面内分享按钮
				console.log(res.target)
			}
			return {
				title: '',
				path: '/pages/index/index',
			}
		},
		onReady() {

		},
		methods: {
			imgtap(e){
				e.ignore()
			},
			//获取注册情况
			getlogin() {
				if (uni.getStorageSync('islogin')) {
					this.$data.islogin = true
					this.getTodaydaka(false)
				} else if (uni.getStorageSync('islogin').length == 0) {
					//获取云端是否注册
					db.collection('user').get({
						success: (res) => {
							if (res.data[0]) {
								this.$data.islogin = true
								uni.setStorageSync('userData', res.data[0].userData);
								uni.setStorageSync('islogin', true);
								uni.setStorageSync('openid', res.data[0]._openid);
								uni.setStorageSync('phoneNum', res.data[0].phoneNum);
								// 获取今日打卡情况
								this.getTodaydaka(false)
								//第二次登陆输入手机号
							}

						}
					})
				}
			},
			//获取今日任务
			getToddayRenwu() {
				uni.showLoading({
					mask: true,
				});
				db.collection('renwu').where({
					date: _.gte(new Date(new Date(new Date().toLocaleDateString()).getTime())).and(_.lte(new Date(new Date(
						new Date()
						.toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1)))
				}).get({
					success: (res) => {
						uni.hideLoading()
						if (res.data.length !== 0) {
							var date = res.data[0].date
							this.$data.ToddayRenwu = res.data[0]
							this.$data.isToddayRenwu = true
						} else {
							this.$data.isToddayRenwu = false
						}
					}
				})
			},
			//获取输入电话
			onKeyInput: function(event) {
				this.$data.phoneNum = event.target.value
			},
			//检查手机号
			cheakPhoneNum() {
				console.log(this.$data.isphoneNum)
				if (this.$data.isphoneNum) {
					this.Sign()
				} else {
					//判断手机号
					let phonereg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
					let phone = this.$data.phoneNum
					if (phone.length == 0) {
						wx.showToast({
							title: '输入的手机号为空',
							icon: 'none'
						})
						return false;
					} else if (phone < 11) {
						wx.showToast({
							title: '手机号长度有误！',
							icon: 'none'
						})
						return false;
					} else if (!phonereg.test(phone)) {
						wx.showToast({
							title: '手机号有误！',
							icon: 'none'
						})
						return false;
					} else {
						var data = {
							phoneNum: this.$data.phoneNum
						}
						wx.cloud.callFunction({
							name: 'echo',
							data: {
								action: "upDateUser",
								data: JSON.stringify(data)
							}
						}).then(res => {
							console.log(res)
							if (res.result.stats.updated == 1) {
								wx.showToast({
									title: '手机号更新成功！',
									icon: 'none'
								})
								uni.setStorageSync('phoneNum', phone);
								this.$data.isphoneNum = true
							}
						}).catch(err => {
							console.log(err)
						})
					}
				}
			},
			join() {
				//存储注册信息
				var data = {
					phoneNum: '',
					signTime: new Date(),
					userData: '',
					city: '',
					nickName: '',
					avatarUrl: '',
					userInc: 0
				}
				uni.showLoading({
					mask: true,
				});
				db.collection('user').add({
					data: data,
					success: (res) => {
						console.log()
						uni.setStorageSync('userId', res._id);
						//获取openid
						wx.cloud.callFunction({
							name: 'login',
							success: res => {
								uni.hideLoading()
								wx.showToast({
									title: '加入成功！',
									icon: 'none'
								})
								uni.setStorageSync('openid', res.result.openid);
								uni.setStorageSync('userData', '');
								this.$data.islogin = true
								uni.setStorageSync('istodaysign', true);
								uni.setStorageSync('phoneNum', '');
								// 获取今日打卡情况
								this.getTodaydaka(true)
							},
						})
					}
				})


			},
			//获取用户信息
			getuserinfo(e) {
				if (e.detail.rawData == undefined) {
					wx.showToast({
						title: '请授权登陆！',
						icon: 'none'
					})
				} else {
					if (uni.getStorageSync('userData').length == 0) {
						uni.setStorageSync('userData', e.target.userInfo);
						var data = {
							phoneNum: uni.getStorageSync('phoneNum'),
							userData: JSON.stringify(uni.getStorageSync('userData')),
							city: uni.getStorageSync('userData').city,
							nickName: uni.getStorageSync('userData').nickName,
							avatarUrl: uni.getStorageSync('userData').avatarUrl,
						}
						wx.cloud.callFunction({
							name: 'echo',
							data: {
								action: "upDateUser",
								data: JSON.stringify(data)
							}
						}).then(res => {
							console.log(res)
							if (res.result.stats.updated == 1) {
								wx.showToast({
									title: '个人信息更新成功！',
									icon: 'none'
								})
								this.cheakPhoneNum()
							} else {
								wx.showToast({
									title: '个人信息更新失败！',
									icon: 'none'
								})
							}

						}).catch(err => {
							console.log(err)
						})
					} else {
						this.cheakPhoneNum();
					}

				}
			},
			getTodaydaka(isFrist) {
				console.log(isFrist)
				// 获取今日打卡情况
				db.collection('sign').where({
					signTime: _.gte(new Date(new Date(new Date().toLocaleDateString()).getTime())).and(_.lte(new Date(new Date(new Date()
						.toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1)))
				}).get({
					success: (res) => {
						//查询到数据
						if (res.data.length !== 0) {
							uni.setStorageSync('istodaysign', true);
							this.$data.istodaysign = true
							uni.setStorageSync('toadySignId', res.data[0]._id);
						} else {
							this.getToddayRenwu()
						}
						//第二次登陆输入手机号
						console.log(isFrist)
						console.log(uni.getStorageSync('phoneNum').length !== 0)
						console.log((uni.getStorageSync('phoneNum').length !== 0) == isFrist)
						if ((uni.getStorageSync('phoneNum').length !== 0) == isFrist) {
							this.$data.isphoneNum = false
						}
					}
				})
			},
			lookSign() {
				//查询历史打卡信息
				db.collection('sign').orderBy('signTime', 'desc').get({
					success: (res) => {
						this.$data.show = true
						this.$data.signData = res.data
					}
				})
			},
			lookImage(e) {
				//预览打卡照片
				wx.previewImage({
					urls: [e]
				})
			},
			Sign() {
				//上传打卡信息
				wx.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: res => {
						const filePath = res.tempFilePaths[0]
						const cloudPath = uni.getStorageSync('openid') + "/" + Date.parse(new Date()) + filePath.match(/\.[^.]+?$/)[0];
						uni.showLoading({
							mask: true,
						});
						wx.cloud.uploadFile({
							cloudPath,
							filePath, // 文件路径
							success: res => {
								//整理时间戳
								var getFullYear = new Date().getFullYear()
								var getMonth = new Date().getMonth() + 1
								var getDate = new Date().getDate()
								var getHours = new Date().getHours()
								var getMinutes = new Date().getMinutes()
								var getSeconds = new Date().getSeconds()
								if (getMonth < 10) {
									getMonth = "0" + getMonth
								}
								if (getDate < 10) {
									getDate = "0" + getDate
								}
								if (getHours < 10) {
									getHours = "0" + getHours
								}
								if (getMinutes < 10) {
									getMinutes = "0" + getMinutes
								}
								if (getSeconds < 10) {
									getSeconds = "0" + getSeconds
								}

								var data = {
									fileID: res.fileID,
									signTime: new Date(),
									signTime2: `${getFullYear}-${getMonth}-${getDate} ${getHours}:${getMinutes}:${getSeconds}`,
									userData: uni.getStorageSync('userData'),
									city: JSON.parse(uni.getStorageSync('userData')).city,
									nickName: JSON.parse(uni.getStorageSync('userData')).nickName,
									avatarUrl: JSON.parse(uni.getStorageSync('userData')).avatarUrl,
									likeList: [],
									likeOpenid: [],
									shenhe: false,
									post: ''
								}
								var that = this
								//上传打卡信息
								db.collection('sign').add({
									data: data,
									success: res => {
										uni.hideLoading()
										//获取订阅消息权限
										const tmplIds = [
											"ydP6R_QsFibhUxv_RBZ4Xb-MQtAOjX3i6GMEVCZznYM",
											"KTBWJIS4PKCwTDikQRDqLv_YmGnSAtKaFZCCWrjT3dE",
											"KTBWJIS4PKCwTDikQRDqLv_YmGnSAtKaFZCCWrjT3dE"
										];
										wx.requestSubscribeMessage({
											tmplIds: tmplIds,
											success: res => {
												console.log("订阅消息API调用成功：", res)
											}
										})

										this.$data.istodaysign = true
										this.$data.toadySignId = res._id
										uni.setStorageSync('toadySignId', res._id)
										uni.setStorageSync('istodaysign', true)
										//this.getRanking()
										//this.userInc()

										//this.subscribeMessage()

									}
								})
							},
							fail: err => {
								// handle error
								uni.hideLoading()
								wx.showToast({
									title: err,
									icon: 'none'
								})
							}
						})
					}
				})

			},
			subscribeMessage() {
				const tmplIds = [
					"ydP6R_QsFibhUxv_RBZ4Xb-MQtAOjX3i6GMEVCZznYM",
					"KTBWJIS4PKCwTDikQRDqLv_YmGnSAtKaFZCCWrjT3dE",
					"KTBWJIS4PKCwTDikQRDqLv_YmGnSAtKaFZCCWrjT3dE"
				];
				wx.requestSubscribeMessage({
					tmplIds: tmplIds,
					success: res => {
						console.log("订阅消息API调用成功：", res)
					}
				})
			},
			//获取排名情况
			getRanking() {
				wx.cloud.callFunction({
					name: 'echo',
					data: {
						action: "getRanking"
					}
				}).then(res => {
					wx.showToast({
						title: `您是全国第${res.result.total}名打卡成功！`,
						icon: 'none'
					})

				}).catch(err => {
					console.log(err)
				})
			},
			userInc() {
				//打卡次数加1
				wx.cloud.callFunction({
					name: 'echo',
					data: {
						action: "userInc"
					}
				}).then(res => {
					console.log(res)
				}).catch(err => {
					console.log(err)
				})
			},
			goTosharePage(e) {
				if (e == true) {
					e = uni.getStorageSync('toadySignId')
				}
				var url = `/pages/index/share?toadySignId=${e}`

				const tmplIds = [
					"ydP6R_QsFibhUxv_RBZ4Xb-MQtAOjX3i6GMEVCZznYM",
					"KTBWJIS4PKCwTDikQRDqLv_YmGnSAtKaFZCCWrjT3dE",
					"KTBWJIS4PKCwTDikQRDqLv_YmGnSAtKaFZCCWrjT3dE"
				];
				wx.requestSubscribeMessage({
					tmplIds: tmplIds,
					success: res => {
						wx.navigateTo({
							url
						})
					}
				})
			}
		}
	}
</script>
<style >

	.indexBody {
		padding: 0 48rpx;
		position: fixed;
		bottom: -1rpx;
		width: 100%;
	    /* background: linear-gradient(top, rgba(225,225,225,0.8) 0%,rgba(225,225,225,1) 15%,rgba(225,225,225,1) 100%) */
		/* Permalink - use to edit and share this gradient: http://colorzilla.com/gradient-editor/#ffffff+0,ffffff+100&0+0,1+20 */
		background: -moz-linear-gradient(top, rgba(255,255,255,0.8) 0%, rgba(255,255,255,1) 20%, rgba(255,255,255,1) 100%); /* FF3.6-15 */
		background: -webkit-linear-gradient(top, rgba(255,255,255,0.8) 0%,rgba(255,255,255,1) 20%,rgba(255,255,255,1) 100%); /* Chrome10-25,Safari5.1-6 */
		background: linear-gradient(to bottom, rgba(255,255,255,0.8) 0%,rgba(255,255,255,1) 20%,rgba(255,255,255,1) 100%); /* W3C, IE10+, FF16+, Chrome20+, Opera12+, Safari7+ */
		filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00ffffff', endColorstr='#ffffff',GradientType=0 ); /* IE6-9 */
	}

	.inputBar {
		margin-bottom: 30px;
		margin-top: 40px;
		width: 654rpx;
	}

	.phoneInput {
		margin: 24rpx 100rpx;
		height: 76rpx;
		border-radius: 5px;
		font-size: 28rpx;
		padding: 5rpx 24rpx;
		line-height: 78rpx;
	}

	.phoneInputplaceholder {
		color: #FFFFFF;
	}

	.joinBtn {
		margin: 24rpx 100rpx;
		font-size: 28rpx;
		line-height: 88rpx;
	}

	.u-node {
		width: 44rpx;
		height: 44rpx;
		border-radius: 100rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		background: #d0d0d0;
	}

	.u-order-title {
		color: #333333;
		font-weight: bold;
		font-size: 32rpx;
	}

	.u-order-desc {
		color: rgb(150, 150, 150);
		font-size: 28rpx;
		margin-bottom: 6rpx;
	}

	.u-order-time {
		color: rgb(200, 200, 200);
		font-size: 20rpx;
	}

	.wanfa {
		font-size: 28rpx;
		text-align: center;
		color: #d0d0d0;
	}

	.wanfaicon {
		display: inline-block;
	}
</style>
